package com.tianpengtech.common.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket")
public class WebSocket {
    private static final AtomicInteger onlineCount = new AtomicInteger(0);
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();
    private String nickname = "";
    private Session session;


    public WebSocket() {
        nickname = "访客" + onlineCount.getAndIncrement();
    }

    @OnOpen
    public void onopen(Session session) {
        System.out.println("连接成功");
        this.session = session;
        webSocketSet.add(this);
        String message = String.format("[%s,%s]", nickname, "加入聊天室");
        broadcast(message);
        System.out.println("onOpen");
    }

    @OnClose
    public void onclose(Session session) {
        webSocketSet.remove(this);
        String message = String.format("[%s,%s]", nickname, "离开了聊天室链接");
        broadcast(message);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        //这里当然会打印true
        System.out.println(this.session == session);
        broadcast(String.format("%s:%s", nickname, filter(message)));
    }

    private void broadcast(String info) {
        for (WebSocket w : webSocketSet) {
            try {
                synchronized (WebSocket.class) {
                    w.session.getBasicRemote().sendText(info);
                }
            } catch (IOException e) {
                System.out.println("向客户端" + w.nickname + "发送消息失败");
                webSocketSet.remove(w);
                try {
                    w.session.close();
                } catch (IOException e1) {
                }
                String message = String.format("[%s,%s]", w.nickname, "已经断开链接");
                broadcast(message);
            }

        }
    }

    public static String filter(String message) {
        if (message == null) {
            return null;
        }
        return message;
    }

}
